package client

import (
	"context"
	"google.golang.org/grpc"
	"order-module/order-rpc/proto/good"
)

type Handler func(ctx context.Context, in good.GoodClient) (interface{}, error)

func GoodClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8085", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := good.NewGoodClient(dial)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	defer dial.Close()
	return res, nil
}

func UserRegister(ctx context.Context, i *good.UserRegisterReq) (*good.UserRegisterResp, error) {
	client, err := GoodClient(ctx, func(ctx context.Context, in good.GoodClient) (interface{}, error) {
		register, err := in.UserRegister(ctx, i)
		if err != nil {
			return nil, err
		}
		return register, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*good.UserRegisterResp), nil
}

func GoodCreate(ctx context.Context, i *good.GoodCreateReq) (*good.GoodCreateResp, error) {
	client, err := GoodClient(ctx, func(ctx context.Context, in good.GoodClient) (interface{}, error) {
		create, err := in.GoodCreate(ctx, i)
		if err != nil {
			return nil, err
		}
		return create, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*good.GoodCreateResp), nil
}

func GoodList(ctx context.Context, i *good.GoodListReq) (*good.GoodListResp, error) {
	client, err := GoodClient(ctx, func(ctx context.Context, in good.GoodClient) (interface{}, error) {
		list, err := in.GoodList(ctx, i)
		if err != nil {
			return nil, err
		}
		return list, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*good.GoodListResp), nil
}

func GoodOrder(ctx context.Context, i *good.GoodOrderReq) (*good.GoodOrderResp, error) {
	client, err := GoodClient(ctx, func(ctx context.Context, in good.GoodClient) (interface{}, error) {
		order, err := in.GoodOrder(ctx, i)
		if err != nil {
			return nil, err
		}
		return order, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*good.GoodOrderResp), nil
}
